package org.example.kunkun_filter.controller;

import org.example.kunkun_filter.dao.ApiResponse;
import org.example.kunkun_filter.dao.UrlDataResponse;
import org.example.kunkun_filter.utils.DouyinDownloaderUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;

@RestController
@RequestMapping("cli")
public class DownloaderController {

    // 平台解析器映射表 - 存储平台名称和对应的解析函数
    private static final Map<String, Function<String, UrlDataResponse>> PLATFORM_PARSERS = new HashMap<>();

    // 平台识别配置 - 使用List存储多个配置项，便于后续扩展
    private static final List<PlatformConfig> PLATFORM_CONFIGS = Arrays.asList(
            new PlatformConfig("douyin", new String[]{"douyin", "tiktok", "iesdouyin", "v.douyin.com"}),
            new PlatformConfig("bilibili", new String[]{"bilibili", "b23.tv"}),
            new PlatformConfig("kuaishou", new String[]{"kuaishou", "gifshow"}),
            new PlatformConfig("xiaohongshu", new String[]{"xiaohongshu", "xhslink"})
    );

    // 静态初始化块 - 注册已实现的平台解析器
    static {
        // 注册抖音解析器
        PLATFORM_PARSERS.put("douyin", url -> {
            try {
                return DouyinDownloaderUtils.extractDownloadUrls(url);
            } catch (Exception e) {
                throw new RuntimeException("抖音解析失败: " + e.getMessage(), e);
            }
        });
        
        // 未来添加其他平台解析器只需在这里注册即可
    }

    @PostMapping("parse")
    public ResponseEntity<ApiResponse<UrlDataResponse>> parse(@RequestBody ParseRequest request) {
        try {
            String url = request.getUrl();
            
            // 1. 验证URL是否有效
            if (url == null || url.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body((ApiResponse<UrlDataResponse>) ApiResponse.error("URL不能为空"));
            }

            // 2. 分析URL来自哪个平台
            String platform = identifyPlatform(url);
            if (platform == null) {
                return ResponseEntity.badRequest()
                        .body((ApiResponse<UrlDataResponse>) ApiResponse.error("无效链接"));
            }

            // 3. 检查是否支持该平台的解析
            Function<String, UrlDataResponse> parser = PLATFORM_PARSERS.get(platform);
            if (parser == null) {
                return ResponseEntity.badRequest()
                        .body((ApiResponse<UrlDataResponse>) ApiResponse.error("暂不支持该平台"));
            }

            // 4. 使用对应的平台解析器解析URL
            UrlDataResponse result = parser.apply(url);

            // 5. 验证解析结果
            if (result == null || result.getDataUrl() == null || result.getDataUrl().isEmpty()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body((ApiResponse<UrlDataResponse>) ApiResponse.error("未找到可下载的资源"));
            }

            // 6. 返回成功响应
            return ResponseEntity.ok(
                    ApiResponse.success("解析成功", result)
            );
        } catch (Exception e) {
            // 7. 异常处理
            String errorMessage = e.getMessage();
            if (errorMessage == null || errorMessage.isEmpty()) {
                errorMessage = "解析失败，请稍后重试";
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body((ApiResponse<UrlDataResponse>) ApiResponse.error("解析失败：" + errorMessage));
        }
    }

    /**
     * 根据URL中的关键字符识别平台
     * @param url 要解析的URL
     * @return 平台标识，如果没有识别到关键字符则返回null
     */
    private String identifyPlatform(String url) {
        url = url.toLowerCase();
        
        // 遍历所有平台配置，检查URL是否包含对应平台的关键字符
        for (PlatformConfig config : PLATFORM_CONFIGS) {
            for (String keyword : config.getKeywords()) {
                if (url.contains(keyword)) {
                    return config.getPlatform();
                }
            }
        }
        
        // 如果没有识别到任何关键字符，则返回null表示无效链接
        return null;
    }

    /**
     * 平台配置类，用于存储平台名称和对应的关键字符
     */
    private static class PlatformConfig {
        private final String platform;
        private final String[] keywords;
        
        public PlatformConfig(String platform, String[] keywords) {
            this.platform = platform;
            this.keywords = keywords;
        }
        
        public String getPlatform() {
            return platform;
        }
        
        public String[] getKeywords() {
            return keywords;
        }
    }

    /**
     * 定义请求参数的静态内部类
     */
    public static class ParseRequest {
        private String url;
        
        public String getUrl() {
            return url;
        }
        
        public void setUrl(String url) {
            this.url = url;
        }
    }
}
